<template>
	<div class="demo-container" id="cif-app">
		<!-- <Loading v-if="state.loading" v-model:show="loading"></Loading> -->
		<div class="loader" v-if="state.loading"></div>
		<div v-show="!state.loading" id="gac-mount" />
		<div id="gac-mount" />
	</div>
</template>

<script>
export default { name: 'Edit' };
</script>
<script setup>
import { onMounted, reactive, toRefs } from 'vue';
import CIF from '@CIF';
// import { usePrimaryStore } from '@/store';
import * as MYSVIEW_API from '@CIF/API/api';
import _ from 'lodash';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import { resetMessage } from '@/utils/message';
// import Loading from './Loading.vue';
import { getLocalstorage } from '@/utils/localstorage';
import StorageHelper from '@/views/CIF/Runtime/Global/storage';

// const store = usePrimaryStore();
let appCfg = {
	appId: '',
	appName: '',
	referenceComponent: [],
	componentTree: '',
	theme: {}
}; // 应用配置
const state = reactive({
	appId: '', // 应用id, 与 route 中 param 路径对应
	// appCfg: {}, // 应用配置
	themeLibrary: [], // 应用主题配置
	cpntLibrary: [],
	loading: true
});

function getQueryVariable(variable) {
	const query = window.location.search.substring(1);
	const vars = query.split('&');
	for (let i = 0; i < vars.length; i++) {
		const pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return 'test';
}
// 获取和处理组件库数据，并将其格式化为树形结构
const fetchComponentLibrary = async () => {
	return new Promise((resolve = () => {}) => {
		MYSVIEW_API.getComponentLibraryAll().then((res) => {
			const cpntLibraryEntrys = _.get(res, 'data', []);
			state.cpntLibrary = cpntLibraryEntrys
				.map((entry) => {
					return {
						...entry,
						package: _.get(entry, 'componentPackages', []).map((x) => {
							return {
								name: _.get(entry, 'cpntName'),
								version: _.get(entry, 'cpntVersion'),
								filePath: x.filePath,
								fileName: x.fileName
							};
						})
					};
				})
				.filter((x) => !_.isEmpty(x.package));
			resolve(state.cpntLibrary);
		});
	});
};

const fetchAllThemeConfiguration = async () => {
	return new Promise((resolve = () => {}) => {
		MYSVIEW_API.getThemeConfiguration().then((res) => {
			state.themeLibrary = res;
			resolve(state.themeLibrary);
		});
	});
};

const fetchApplicationConfiguration = (appId = '') => {
	return new Promise((resolve = () => {}) => {
		// 通过 API 获取应用配置
		return MYSVIEW_API.getApplicationConfiguration(appId).then((res) => {
			/**
			 *对于容器类组件和组件树的设计思考
			 * 组件树支持组件嵌套，但组件树另外提供文件夹的形式对组件进行整理归类，组件可以拖动到文件夹里
			 * 文件夹支持改名，有唯一 id，支持文件夹嵌套
			 * 容器类组件单独开发选用，不作为内置组件
			 * 在组件树中仅容器类型的组件支持嵌套，即仅文件夹和容器类组件允许有子节点
			 *
			 */
			const refrenceComponentStr = _.get(res, 'data.referenceComponent');
			appCfg = {
				appId: _.get(res, 'data.id'),
				appName: _.get(res, 'data.applicationName'),
				referenceComponent: JSON.parse(
					_.isEmpty(refrenceComponentStr) ? '[]' : refrenceComponentStr
				),
				componentTree: _.get(res, 'data.componentTree') || [],
				theme: {
					primary: document.documentElement.style.getPropertyValue('--theme-color') || '#0c75c5'
				},
				baseMap: res?.data?.baseMap || {},
				defaultEngineType: res?.data?.defaultType
			};
			resolve(appCfg);
		});
	});
};

// const cifMode = computed(() => {
// 	let mode = getQueryVariable('mode');
// 	if (mode === '0') {
// 		return RUNTIME_CFG_ENUM.PREVIEW_MODE;
// 	} else if (mode === '1') {
// 		return RUNTIME_CFG_ENUM.EDIT_MODE;
// 	} else {
// 		return RUNTIME_CFG_ENUM.PRODUCTION_MODE;
// 	}
// });

const fetchStationInfo = (appId) => {
	return new Promise((resolve = () => {}) => {
		// TODO: 从后端提供的本应用里默认引擎的默认绑定服务的API接口中解析出图形服务站点的私钥密钥，以便后续传入CIF中进行登录，获取服务站点token
		// const responseDataFromAPI = someApi.fetch(id);
		const responseDataFromAPI = [
			{
				station_name: 'fakeBimBase',
				origin: 'http://39.174.170.163:8082',
				engine_type: 'BIMBase',
				ak: 'acme',
				sk: 'acmesecret'
			}
		];
		resolve(responseDataFromAPI);
	});
};

const initOnline = async () => {
	const appId = getQueryVariable('applicationId');
	await fetchAllThemeConfiguration();
	const appConfig = await fetchApplicationConfiguration(appId);
	// todo 设置 DEFAULT_ENGINE_TYPE和 APPLICATION_BASEMAP 放在此处是否合理？
	StorageHelper.set(RUNTIME_CFG_ENUM.DEFAULT_ENGINE_TYPE, appConfig.defaultEngineType);
	StorageHelper.set(RUNTIME_CFG_ENUM.APPLICATION_BASEMAP, appConfig.baseMap);
	await fetchComponentLibrary();
	const akskPair = await fetchStationInfo(appId);
	const stationInfo = akskPair[0];

	_.set(window, 'cif.config.logger.enable', true);
	// appCfg.mode = RUNTIME_CFG_ENUM.PREVIEW_MODE;
	appCfg.mode = RUNTIME_CFG_ENUM.EDIT_MODE;
	appCfg.contextOptions = {
		webgl2: true
		// sceneData: {
		// 	// sceneUrl: 'urn:bimbox.object:first_bucket/028129403f72956c458240af0ffe8a53|rvt-lod', // TODO: 应用配置中的默认服务
		// 	loadOptions: {
		// 		origin: stationInfo.origin,
		// 		stationName: stationInfo.station_name,
		// 		ak: stationInfo.ak || '',
		// 		sk: stationInfo.sk || ''
		// 	}
		// },
		// engineType: 'SUPERMAP'
	};

	CIF.configuate(appCfg, state.cpntLibrary, state.themeLibrary);
	CIF.init('gac-mount')
		.then(([cpntTree, errMsg]) => {
			state.loading = false;
			errMsg?.length !== 0 &&
				resetMessage({
					message: errMsg.join(', '),
					type: 'error',
					duration: 2 * 1000
				});
			// test code start
			// ComponentTreeHelper.addNewInstancesToTreeByDefIds(cpntTree, ["1505824346122227713"])
			// setTimeout(() => {
			//   ComponentTreeHelper.addNewInstancesToTreeByDefIds(cpntTree, ["1442748567243460609"])
			//   ComponentTreeHelper.addNewInstancesToTreeByDefIds(cpntTree, ["1442748962502086658"])
			// }, 1000)
			// setTimeout(() => {
			//   const treeData = ComponentTreeHelper.saveTree(cpntTree)
			//   MYSVIEW_API.updateApplicationConfiguration(appId, {
			//     componentTree: treeData,
			//     referenceComponent: zip(JSON.stringify(StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_REFRENCE_COMPONENT_CFG))),
			//     themeId: StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_THEME_ID),
			//   }).then((res) => {
			//     console.log("save cif app config", res.data)
			//   })
			// }, 30000)
			// test code end
		})
		.catch((e) => {
			console.log('CIF run error', e);
		});
};
window.addEventListener('message', (e) => {
	if (e.data.key === 'aide') {
		localStorage.setItem('access_token', e.data.token);
	}
});
onMounted(() => {
	let token = getLocalstorage('access_token');
	const a = setInterval(() => {
		token = getLocalstorage('access_token');
		if (token) {
			clearInterval(a);
			initOnline();
		}
	}, 300);
});
defineExpose({ ...toRefs(state) });
</script>

<style lang="scss" scoped>
/* HTML: <div class="loader"></div> */
.loader {
	--s: 25px;
	--g: 5px;

	width: calc(3 * (1.353 * var(--s) + var(--g)));
	display: grid;
	justify-items: end;
	aspect-ratio: 3;
	overflow: hidden;
	--_m: linear-gradient(90deg, #0000, #000 15px calc(100% - 15px), #0000);
	-webkit-mask: var(--_m);
	mask: var(--_m);
	position: fixed;
	left: 50%;
	top: 48%;
}
.loader:before {
	content: '';
	width: 200%;
	background: linear-gradient(90deg, var(--primary) 50%, #0000 0),
		conic-gradient(
			from -90deg at var(--s) calc(0.353 * var(--s)),
			#fff 135deg,
			#666 0 270deg,
			#aaa 0
		);
	background-blend-mode: multiply;
	--_m: linear-gradient(
			to bottom right,
			#0000 calc(0.25 * var(--s)),
			#000 0 calc(100% - calc(0.25 * var(--s)) - 1.414 * var(--g)),
			#0000 0
		),
		conic-gradient(from -90deg at right var(--g) bottom var(--g), #000 90deg, #0000 0);
	-webkit-mask: var(--_m);
	mask: var(--_m);
	background-size:
		calc(100% / 3) 100%,
		calc(100% / 6) 100%;
	-webkit-mask-size: calc(100% / 6) 100%;
	mask-size: calc(100% / 6) 100%;
	-webkit-mask-composite: source-in;
	mask-composite: intersect;
	animation: l10 1s infinite linear;
}
@keyframes l10 {
	to {
		transform: translate(calc(100% / 3));
	}
}
.demo-container {
	width: 100%;
	height: 100vh;
	background: var(--black);
}

.cpnt-container {
	position: fixed;
	top: 0;
	left: 0;
	width: 350px;
	height: 700px;
	border: 1px solid #06ceae;
	box-sizing: border-box;
	border-radius: 5px;
	background: rgba(18, 18, 18, 0.85);
	z-index: 999999;

	.title {
		height: 36px;
		margin: 0;
		padding: 0 10px;
		border-bottom: 1px solid #06ceae;
		/* background-color: rgba(0, 0, 0, 0.2); */
		font-size: 14px;
		line-height: 36px;
		color: rgba(255, 255, 255, 0.92);
		text-align: right;
	}

	.body {
		/* background: rgba(0, 0, 0, 0.2); */
		width: 100%;
		height: calc(100% - 37px);
	}

	// .fks-loading-mask {
	// 	/* background: rgba(0, 0, 0, 0.2); */
	// }

	.el-tree__empty-text {
		color: #000;
	}

	.close {
		color: rgba(255, 255, 255, 0.92);
		position: absolute;
		top: 9px;
		left: 10px;
		cursor: pointer;
	}
}

.cpnt-container-show {
	position: fixed;
	top: 0;
	right: 0;
	z-index: 999999;
}

.folder {
	margin-left: 10px;
	cursor: pointer;
}

.cpnt-library-table {
	.search {
		margin-bottom: 10px;
	}

	.el-tree {
		height: 500px;
		color: rgba(255, 255, 255, 0.92);
	}
}

.cpnt-tree {
	color: #000;
	overflow-y: scroll;
	padding-left: 6px;
}

.cpnt-tree-table {
	display: flex;
	width: 100%;
	height: 36px;
	line-height: 36px;
	text-align: center;
	font-size: 14px;
	color: rgba(255, 255, 255, 0.92);

	&.header {
		color: rgba(255, 255, 255, 0.92);
		/* background: rgba(0, 0, 0, 0.2); */
	}

	.name {
		flex: auto;
		min-width: 110px;

		&.tree {
			text-align: left;
		}
	}

	.cpnt-name {
		text-align: left;
		text-indent: 2rem;
	}

	.type {
		width: 80px;
		padding-right: 4px;

		&.tree {
			padding-right: 0;
		}
	}

	.version {
		width: 80px;
		/* &.tree {
      border-left: 1px solid #eee;
    } */
	}

	::v-deep .el-button {
		padding: 2px 9px;
		height: 22px;
	}
}
</style>
